package com.cheng.rocket;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.cheng.mapper.SummaryPlugMapper;
import com.cheng.pojo.po.Summary;
import com.cheng.pojo.vo.RocketPeople;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.lang.Thread.sleep;

@Service
@RocketMQMessageListener(
        topic = "summary",
        selectorExpression = "people",
        consumerGroup = "JXGroup-summary-people"
)
public class PeopleListener implements RocketMQListener<RocketPeople> {

    @Resource
    private SummaryPlugMapper summaryPlugMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void onMessage(RocketPeople rocketPeople) {
        // System.out.println(rocketPeople);
        Summary summary = summaryPlugMapper.selectOne(
                new QueryWrapper<Summary>()
                        .eq("year", rocketPeople.getYear())
                        .eq("unit", rocketPeople.getUnit()));

        if(summary == null){
            return;
        }
        String toName = "";
        if(summary.getPeople() != null && !summary.getPeople().isEmpty()){
            if(summary.getPeople().contains(",")){
                List<String> nameList = new ArrayList<>(Arrays.asList(summary.getPeople().split(",")));

                if(!nameList.contains(rocketPeople.getPeople())){
                    nameList.add(rocketPeople.getPeople());
                }
                toName = String.join(",", nameList);
            }else{
                if(rocketPeople.getPeople().equals(summary.getPeople())){
                    toName = rocketPeople.getPeople();
                }else{
                    // 多个名字，则添加到后面
                    System.out.println(5);
                    toName = summary.getPeople() + "," + rocketPeople.getPeople();
                }
            }
        }else {
            toName = rocketPeople.getPeople();
            System.out.println("审核人为空");
        }
        stringRedisTemplate.delete("summary:edit:"+rocketPeople.getYear());
        int i = summaryPlugMapper.updateById(new Summary().builder().id(summary.getId()).people(toName).build());

        if(i == 1){
            try{
                sleep(500);
            }catch(Exception e){
                System.out.println("休眠中出错");
            }
            stringRedisTemplate.delete("summary:edit:"+rocketPeople.getYear());
        }

    }
}
